package com.immortal.core.module.jpa;

import com.google.common.collect.Lists;
import com.immortal.core.module.res.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;

public abstract class BaseController<E, ID extends Serializable> {

    protected List<String> restApi = Lists.newArrayList();

    @Autowired
    public abstract BaseService getService();

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult get(@PathVariable ID id) {
        if (restApi.contains("get")) {
            Object entity = getService().findById(id);
            return ApiResult.Custom().success().add(entity);
        } else {
            return ApiResult.Custom().failure();
        }

    }


    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getAll() {
        if (restApi.contains("getAll")) {
            List<E> list = getService().findAll();
            return ApiResult.Custom().success().add(list);
        } else {
            return ApiResult.Custom().failure();
        }

    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getByPage(@PageableDefault Pageable pageable) {
        if (restApi.contains("getByPage")) {
            Page<E> data = getService().findAll(pageable);
            return ApiResult.Custom().success().add(data);
        } else {
            return ApiResult.Custom().failure();
        }

    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult save(@ModelAttribute E entity) {
        if (restApi.contains("save")) {
            Object e = getService().save(entity);
            return ApiResult.Custom().success();
        } else {
            return ApiResult.Custom().failure();
        }

    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    @ResponseBody
    public ApiResult update(@ModelAttribute E entity) {
        if (restApi.contains("update")) {
            getService().save(entity);
            return ApiResult.Custom().success();
        } else {
            return ApiResult.Custom().failure();
        }

    }

    @RequestMapping(value = "/del/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public ApiResult delAllByIds(@PathVariable ID[] ids) {
        if (restApi.contains("del")) {
            for (ID id : ids) {
                getService().deleteById(id);
            }
            return ApiResult.Custom().success();
        } else {
            return ApiResult.Custom().failure();
        }

    }
}
